import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_elm/json/response_item.dart';
import 'package:flutter_elm/network/business_api.dart';
import 'package:flutter_elm/network/business_api.dart';
import 'package:flutter_elm/network/food_api.dart';
import 'package:flutter_elm/network/food_api.dart';
import 'package:provider/provider.dart';

import '../components/Base64Img.dart';
import '../components/elmBottomNavigatorBar.dart';
import '../json/business_item.dart';
import '../json/cart_item.dart';
import '../json/food_item.dart';
import '../json/item_model.dart';
import '../network/cart_api.dart';
import '../network/user_api.dart';
import '../store/global_data.dart';

class BusinessInfoPage extends StatefulWidget {
  const BusinessInfoPage({super.key, required this.title});
  final String title;

  @override
  State<BusinessInfoPage> createState() => _BusinessInfoPageState();
}

class _BusinessInfoPageState extends State<BusinessInfoPage> {
  FoodApi foodApi = FoodApi();
  CartApi cartApi = CartApi();


  Future<List<FoodItem>?> getBusinessInfoData(BusinessItem businessItem) async{
    ResponseItem<List<FoodItem>?> resFood = await foodApi.listFoodByBusinessId(businessItem.businessId);
    List<FoodItem>? foodList = resFood.data;
    if(resFood.data!=null){
      String userId = Provider.of<GlobalData>(context, listen: false).getUserId();
      if(userId!=""){
        var resCart = await cartApi.findCartsByUidAndBid(userId, businessItem.businessId);
        if(resCart.code==200){
          List<CartItem> cartList = resCart.data!;
          for(int i=0; i<cartList.length; i++){
            for(int j=0; j<foodList!.length;j++){
              // 购物车里面foodId是唯一的
              if(cartList[i].food.foodId == foodList[j].foodId){
                foodList[j].quantity = cartList[i].quantity;
                businessItem.userCartTotalPrice = businessItem.userCartTotalPrice! + foodList[j].quantity! * foodList[j].foodPrice;
              }
            }
          }
          //这个操作直接改foodList顺序，返回值为void。因此最后一起返回就行了。不能返回foodList.sort
          //注意前面是(a,b),后面是b比a，那么就是降序排列。否则就是升序排列
          foodList!.sort((a, b)=> b.quantity!.compareTo(a.quantity!));
        }//反之就是 没有加到购物车，直接 默认值0就行,也就不用进行排序
      }
      return foodList;
    }
    return null;
  }


  double calCartTotalPrice(List<FoodItem> foodList){
    double cartTotalPrice = 0;
    for(int i=0;i<foodList.length;i++){
      cartTotalPrice = cartTotalPrice + foodList[i].foodPrice* foodList[i].quantity!;
    }
    return cartTotalPrice;
  }

  @override
  Widget build(BuildContext context) {
    BusinessItem businessItem = ModalRoute.of(context)?.settings.arguments as BusinessItem;

    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blueAccent.shade400,
          title: Text("${widget.title}",style: TextStyle(color: Colors.white),),
          centerTitle: true,
          automaticallyImplyLeading: false,
        ),
        bottomNavigationBar: ElmBottomNavigatorBar(),
        body: FutureBuilder(
          future: getBusinessInfoData(businessItem),
          builder: (context, snpashot){
          switch(snpashot.connectionState) {
            case ConnectionState.done:
              List<FoodItem>? foodList = snpashot.data;
              return Container(
                child: Column(
                  children: [
                    Expanded(
                        child: CustomScrollView(
                          slivers: [
                            SliverAppBar(
                              toolbarHeight: 250,//这个得确定，否则appBar有固定高度
                              // backgroundColor: Colors.grey,
                              automaticallyImplyLeading: false,
                              title: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [Expanded(
                                  child: Column(
                                    children: [
                                      Image.memory(Base64Decoder().convert(businessItem.businessImg.split(",")[1]),scale: 1,),
                                      Padding(padding: EdgeInsets.only(bottom: 15)),
                                      Text(businessItem.businessName,style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),),
                                      Padding(padding: EdgeInsets.only(bottom: 5)),
                                      Text("￥${businessItem.starPrice}起送 | ￥${businessItem.deliveryPrice}配送。总价：${businessItem.userCartTotalPrice}",style: TextStyle(fontSize: 15),),
                                      Padding(padding: EdgeInsets.only(bottom: 5)),
                                      Text(businessItem.businessExplain,style: TextStyle(fontSize: 15),),
                                    ],
                                  ),)],
                              ),
                              floating: true,
                              // snap: true,//

                            ),
                            foodList==null
                                ?SliverToBoxAdapter(child:Center(child: Text("没有食物数据",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 20,color: Colors.blueAccent),),))
                                :SliverList(
                              delegate:SliverChildBuilderDelegate((context, index){
                                return InfoListViewItem(foodItem: foodList[index]);
                              },
                                  childCount: foodList.length
                              ),

                            ),
                          ],
                        ),
                    ),
                    Container(
                      height: 80,
                      color: Colors.grey,
                      alignment: Alignment.bottomCenter,
                      child: Row(
                        children: [
                          //这里的size需要和container的高度一致
                          StackTopRightNumberWithIcon(userCartCount: businessItem.userCartCount!, size: 80,)
                        ],
                      )
                    )
                  ],
                ),
              );

            default:
              return Center(child: Text("数据加载中..."),);
          }

          },
        )
    );
  }
}


























class InfoListViewItem extends StatefulWidget {
  const InfoListViewItem({super.key, required this.foodItem});
  final FoodItem foodItem;

  @override
  State<InfoListViewItem> createState() => _InfoListViewItemState();
}

class _InfoListViewItemState extends State<InfoListViewItem> {

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10,vertical: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Base64Img(imgCode: widget.foodItem.foodImg,circleBorderRadius: 10,scale: 1.5,),
                  Padding(padding: EdgeInsets.only(right:15)),
                  Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text( widget.foodItem.foodName,style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),),
                          Padding(padding: EdgeInsets.only(bottom: 10)),
                          Text( widget.foodItem.foodExplain),
                          Padding(padding: EdgeInsets.only(bottom:10)),
                          Text("￥${ widget.foodItem.foodPrice}",style: TextStyle(fontSize: 15),),
                        ],
                  )
                  )
                ],
          )),
          AddNumRemoveButton(num: widget.foodItem.quantity!),
        ],
      )
    );
  }
}




class AddNumRemoveButton extends StatefulWidget {
  AddNumRemoveButton({super.key, required this.num});
  final int num;

  @override
  State<AddNumRemoveButton> createState() => _AddNumRemoveButtonState();
}

class _AddNumRemoveButtonState extends State<AddNumRemoveButton> {
  double btnSize = 24;
  int num = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    num = widget.num;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // transform: Matrix4.translationValues(15, 0, 0.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          num==0?SizedBox():Row(
            children: [
              Container(
                width: btnSize,
                height: btnSize,
                child: IconButton(
                    padding:EdgeInsets.all(0),
                    onPressed: (){numRemove();},
                    icon: Icon(Icons.remove_circle, color: Colors.grey,size:btnSize,)
                ),
              ),
              Padding(padding: EdgeInsets.only(right:4)),
              Text("${num}"),
              Padding(padding: EdgeInsets.only(right:4)),
            ],
          ),
          Container(
            width: btnSize,
            height: btnSize,
            child: IconButton(
                padding:EdgeInsets.all(0),
                onPressed: (){numAdd();},
                icon: Icon(Icons.add_circle, color: Colors.blueAccent,size:btnSize,)
            ),
          ),
        ],
      ),
    );
  }


  numAdd(){
    num = num+1;
    setState(() {

    });
  }

  numRemove(){
    num = num-1;
    setState(() {

    });
  }
}





class StackTopRightNumberWithIcon extends StatelessWidget {
  const StackTopRightNumberWithIcon({super.key, required this.userCartCount,
  required this.size});

  final int userCartCount;
  final double size;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        // borderRadius: BorderRadius.circular(10),
        // color: Colors.grey
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: 75,
            height: 75,
            decoration: BoxDecoration(
              color: Colors.blueAccent,
              border: Border.all(width: 6, color: Colors.grey.shade800),
              borderRadius: BorderRadius.circular(100)
            ),
            child: Icon(
              Icons.shopping_cart,color: Colors.white,
              size: 45,
            ),
          ),
          userCartCount==0?SizedBox():Positioned(
            //消除按钮自带的外边距效果。首先：可以设置为负数。其次，可以看出MaterialButton自带的外边距就是10
              right: -10, top: -9,
              child: CircleWithCenterSingleNum(num: userCartCount, textColor: Colors.white, circleColor: Colors.red,)
          ),
        ],
      ),
    );
  }
}




class CircleWithCenterSingleNum extends StatelessWidget {
  const CircleWithCenterSingleNum({super.key, required this.num, required this.textColor,required this.circleColor});
//注意：如果是要改大小的话，还得琢磨
  final int num;
  final Color textColor;
  final Color circleColor;


  @override
  Widget build(BuildContext context) {
    return Container(
      child: MaterialButton(
        onPressed: (){},
        //背景颜色
        color: circleColor,
        //设置一个完整的圆大小
        height: 28, minWidth:28, padding: EdgeInsets.all(0),
        //圆角边框
        shape: const RoundedRectangleBorder(side:BorderSide.none,borderRadius: BorderRadius.all(Radius.circular(200),),),
        //取消自带的点击水波效果
        splashColor: Colors.transparent, focusColor: Colors.transparent,highlightColor: Colors.transparent,
        //取消自带的阴影效果
        //按钮的阴影 //按钮按下时的阴影高度//未设置点击时的阴影高度
        elevation: 0,highlightElevation: 0,disabledElevation: 0.0,
        child: Text("${num}",style: TextStyle(color: textColor,fontSize: 20),),
      ),
    );
  }
}




